package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.Finance;
import com.itheima.domain.cargo.FinanceExample;
import com.itheima.domain.cargo.Invoice;
import com.itheima.domain.cargo.Shipping;
import com.itheima.service.cargo.FinanceService;
import com.itheima.service.cargo.InvoiceService;
import com.itheima.service.cargo.ShippingService;
import com.itheima.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;

@Controller
@RequestMapping("/cargo/finance")
public class FinanceController extends BaseController {
    @Reference
    private ShippingService shippingService; //委托单
    @Reference
    private InvoiceService invoiceService;//发票
    @Reference
    private FinanceService financeService;

    @RequestMapping(value = "/toFinance", name = "跳转财务新增页面")
    public String toFinance(String id) throws ParseException {
        request.setAttribute("id",id);
        Invoice invoice = invoiceService.findById(id);
        Shipping shipping = shippingService.findById(id);

        Finance finance = new Finance();

        finance.setInvoiceId(invoice.getInvoiceId());
        finance.setFinanceNum(invoice.getJine());
        finance.setCreateTime(new SimpleDateFormat("yyyy-MM-dd").parse(invoice.getIncoiceTime()));
        finance.setPackinglistid(invoice.getHetonghao());
        finance.setPortOfLoading(shipping.getShipmentPort());
        finance.setPortOfDischarge(shipping.getDestinationPort());
        finance.setConsignee(shipping.getHoster());

        request.setAttribute("finance",finance);

        return "/cargo/finance/finance-add";
    }


    //添加 或 修改
    @RequestMapping("/edit")
    public String edit(Finance finance){
//        System.out.println(finance);

        financeService.save(finance);

        return "redirect:/cargo/finance/list.do";
    }
    //分页显示
    @RequestMapping("/list")
    public String list(
            @RequestParam(defaultValue = "1", name = "page") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize){
        FinanceExample financeExample = new FinanceExample();
        PageInfo info = financeService.findByPage(pageNum, pageSize,financeExample);
        request.setAttribute("page", info);
        return "/cargo/finance/finance-list";
    }


    @RequestMapping(value = "/delete", name = "财务单删除")
    public String delete(String id) {
        //调用service删除
        financeService.delete(id);

        //重定向到list方法
        return "redirect:/cargo/finance/list.do";
    }
}
